package server;

import util.Vector;
import vectors.LinkedListVector;
import vectors.Vectors;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.BindException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;

/**
 * Created by IntelliJ IDEA.
 * User: I
 * Date: 23.11.2010
 * Time: 12:32:41
 * To change this template use File | Settings | File Templates.
 */
public class SerialServer {
    private static Socket incoming;
    private static ServerSocket serverSocket;
    private static int port = 8189;
    private static ObjectOutputStream output_object;
    private static ObjectInputStream input_object;

    public static void main(String[] args) {
        getData();
    }

    private static void getData() {
        try {
            serverSocket = new ServerSocket(port);
            incoming = serverSocket.accept();

            output_object = new ObjectOutputStream(incoming.getOutputStream());
            input_object = new ObjectInputStream(incoming.getInputStream());
            String st;
            Vector v1 = null;
            Vector v2 = null;
            Vector sum = null;
            boolean flag = true;
            while (true) {
                st = (String) input_object.readObject();
                //System.out.println("Client data = " + st);
                if (flag) {
                    v1 = new LinkedListVector(st);
                    flag = false;
                } else {
                    v2 = new LinkedListVector(st);
                    sum = Vectors.sumVect(v1, v2);

                    for (int i = 0; i < sum.length(); i++) {
                        System.out.println("sum.getElement(i) = " + sum.getElement(i));
                    }
                    output_object.writeObject(sum.toString());
                    flag = true;
                }
            }

        } catch (BindException e) {
            System.out.println("Program is already running.");
            System.exit(0);
        } catch (SocketException e) {
            System.out.println("Client disconnect.");
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

    }
}
